<template>
  <div class="common-layout">

    <el-container>
      <el-aside>
        <el-page-header  icon="el-icon-d-arrow-left" title="返回" @click="goBack" > </el-page-header>


        <el-row>
          <el-col :span="6">
            <router-link :to="{name:'AddCustomer'}">
              <el-button class="my_button" icon="el-icon-document-copy" type="info">录入客户信息</el-button>
            </router-link>
            </el-col>

        </el-row>
        <el-row>
          <el-col :span="6">
            <el-button
                class="my_button" icon="el-icon-document-copy" type="info">客户管理</el-button>
          </el-col>
        </el-row>

        <el-table
            :data="groupList"
            style="width: 60%"
            :header-cell-style="headClass"
            :cell-style="rowClass"
            class="my_table"
        >

            <el-table-column
                prop="groupName"
                label="分组名称"
                width="180"
                @contextmenu=""
            >
                <template #default="scope">
                  <a @click="getCustomerInfo(1,scope.row.id)" v-on:click.right="selectDeleteGroupId(scope.row.id)" v-on:contextmenu.prevent=" ">{{scope.row.groupName}}</a>
                </template>

            </el-table-column>

        </el-table>

      </el-aside>


      <el-main>
        <div class="handle-box">
        客户类别：
        <el-select v-model="customerQuery.sort" placeholder="请选择" class="handle-select mr10">
          <el-option label="全部" :value=null></el-option>
          <el-option label="重要客户" :value="15"></el-option>
          <el-option label="中等客户" :value="10"></el-option>
          <el-option label="普通客户" :value="5"></el-option>
        </el-select>
        客户姓名：
        <el-input v-model="customerQuery.name" placeholder="请输入" class="handle-input mr10"></el-input>
        客户状态：
        <el-select v-model="customerQuery.status" placeholder="请选择" class="handle-select mr10">
          <el-option label="全部" :value=null></el-option>
          <el-option label="未分析" :value="0"></el-option>
          <el-option label="已分析" :value="1"></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-search" @click="getCustomerInfo()"></el-button>
      </div>

        <el-table
            :data="customerList"
            border
            style="width: 100%"
            :header-cell-style="headClass"
            :cell-style="rowClass"
            class="table"
            ref="multipleTable"
            header-cell-class-name="table-header"
            @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" ></el-table-column>
          <el-table-column prop="name" label="姓名" ></el-table-column>
          <el-table-column prop="professional" label="职业"></el-table-column>
          <el-table-column prop="birthday" label="年龄">
            <template #default="scope">
              {{calcAge(scope.row.birthday)+'岁'}}
            </template>
          </el-table-column>
          <el-table-column align="right">
            <template #header #default="scope">
              <el-button class="my_button" type="text" @click="exportCustomerInfos">
                导出信息
              </el-button>
              <el-button  class="my_button" type="text"  @click="moreVisible = true" icon="el-icon-more">
                更多
              </el-button>
              <el-button
                  class="my_button"
                  type="text"
                  @click="deleteCustomerBatch"
                  icon="el-icon-delete">
              </el-button>
            </template>
            <template #default="scope">
              <router-link :to="{name:'CustomerInfo', params:{id: scope.row.id}}">
                <el-button size="medium" icon="el-icon-edit" id="view-btn" style="margin-right: 20px;">查看</el-button>
              </router-link>

              <router-link :to="{name:'Psy', params:{customerId: scope.row.id}}">
                <el-button
                    type="primary"
                >上传图片</el-button
                >
              </router-link>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页  -->
        <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            style="padding: 30px 0; text-align: center;"
            layout="total, prev, pager, next, jumper"
            @current-change="getCustomerInfo"
        />

        <!-- 编辑更多框 -->
        <el-dialog title="添加到分组" v-model="moreVisible" width="600px">
          <el-table
              :data="groupList"
              @selection-change="handleGroupSelectionChange"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column property="groupName" label="分组名称" width="150"></el-table-column>
            <el-table-column property="count" label="人数" width="200"></el-table-column>
          </el-table>

          <el-button
              type="text"
              icon="el-icon-plus"
              style="margin: 0px 10px"
              @click="addGroup"
          >
          </el-button>
          <el-input
              type="text"
              placeholder="新建分组"
              v-model="group.groupName"
              style="width: 200px"
              maxlength="10"
              show-word-limit
          >
          </el-input>
          <template #footer>
      <span class="dialog-footer">
        <el-button @click="moreVisible = false">取 消</el-button>
        <el-button type="primary" @click="moveCustomer">
          确 定
        </el-button>
      </span>
          </template>
        </el-dialog>

        <!--编辑分组操作框-->
        <div id = "operateDialog">
          <el-dialog v-model="groupOperateVisible" width="12%" >
            <span class="dialog-footer">
              <el-button class="groupOperateButton" @click="addGroupVisible = true">
                新建分组
              </el-button>
                  <br/>
              <el-button @click="deleteGroupById" class="groupOperateButton">
              删除分组
              </el-button>
           </span>
          </el-dialog>
        </div>


        <!-- 编辑新建分组框 -->
        <el-dialog title="新建分组" v-model="addGroupVisible" width="300px">
          <el-input
              type="text"
              placeholder="新建分组"
              v-model="group.groupName"
              style="width: 200px"
              maxlength="10"
              show-word-limit
          >
          </el-input>
          <template #footer>
      <span class="dialog-footer">
        <el-button @click="addGroupVisible = false,groupOperateVisible = false">取 消</el-button>
        <el-button type="primary" @click="addGroup">
          确 定
        </el-button>
      </span>
          </template>
        </el-dialog>
      </el-main>


    </el-container>

  </div>
</template>

<script>
import customer from "@/api/customer/customer";
import group from "@/api/group/group";
import exports from "@/api/util/exports";

export default {
  data() {
    return {
      customerList: null,
      userId: null,
      pageSize: 5,
      currentPage: 1,
      total: 0,
      moreVisible: false,
      groupManageVisible:false,
      groupOperateVisible:false,
      addGroupVisible: false,
      customerQuery: {
        sort: null,
        profession: null,
        name: null,
        status: null,
        groupId: null,
      },
      groupList: null,
      // 选中用户信息
      multipleSelection: [],
      // 选中分组信息
      multipleGroupSelection: [],
      // 选中用户编号
      customerIdSelected: [],
      groupIdSelected: [],
      // 新建分组名称
      group: {
        groupName: null,
        userId: 3376322891317,
      },
      groupId: null,
      groupInitId: null,
      deleteGroupId: null,
    }
  },
  created() {
    let user = JSON.parse(localStorage.getItem("SESSION_KEY_USER"));
    this.userId = user.id;
  },
  beforeMount() {
    this.getGroupInfo();
  },
  mounted() {
  },
  methods: {
    // 表头居中显示
    headClass() {
      return "text-align:center"
    },
    rowClass() {
      return "text-align:center"
    },
    //导出客户信息
    exportCustomerInfos() {
      this.$confirm('此操作将导出选中用户,是否继续?','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        let array = [];
        for (let i = 0; i < this.customerIdSelected.length; i++) {
          let id = {};
          id.id = this.customerIdSelected[i];
          array[i] = id.id;
        }
        array = {array};
        exports.exportCustomerInfo(array).then(response => {
          const content = response
          const blob = new Blob([content])
          const fileName = '客户信息.xlsx'
          if('download' in document.createElement('a')) { // 非IE下载
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
          } else { // IE10+下载
            navigator.msSaveBlob(blob, fileName)
          }
          this.$refs.multipleTable.clearSelection(); // 将已选置为空
          // this.multipleSelection = [] // 置为空
          this.$message({
            type: 'success',
            message: '导出成功',
          })
        }).catch((response) => {
          console.log("error:" + response)
        })

      }).catch(() => {
        this.$refs.multipleTable.clearSelection(); // 将已选置为空
        this.$message({
          type: 'info',
          message: '已取消导出',
        })
      })

    },
    // 页面跳转
    goBack() {
      this.$router.replace('/customer/show')
    },
    initCustomer() {
      this.getCustomerInfo()
    },
    initGroup() {
      this.getGroupInfo()
    },
    // 选择要删除的分组
    selectDeleteGroupId(groupId) {
      this.deleteGroupId = groupId;
      this.groupOperateVisible = true
    },
    // 删除分组
    deleteGroupById() {
      this.$confirm('此操作将删除分组, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        group.deleteGroup(this.deleteGroupId).then(response => {
          this.initGroup()
          this.groupOperateVisible = false
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
          return response;
        }).catch((response) => {
          this.groupOperateVisible = false
          this.$message({
            type: 'error',
            message: '分组内仍有客户，删除失败！'
          })
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除',
        })
      })
    },
    getCustomerInfo(currentPage = 1, id = this.groupInitId) {
      this.currentPage = currentPage
      this.customerQuery.groupId = id
      this.groupInitId = id
      customer.getCustomerInfo(this.userId, this.currentPage, this.pageSize, this.customerQuery)
        .then((response) => {
          this.customerList = response.data.item.records;
          this.total = response.data.item.total;
      }).catch(error => {
        console.log(error);
        this.$message({
          type: 'error'
        })
      })
    },
    getGroupInfo() {
      group.getGroupInfo(this.userId)
        .then((response) => {
          this.groupList = response.data.list;
          this.groupInitId = this.groupList[0].id
          this.getCustomerInfo()
        }).catch(error => {
          console.log(error);
          this.$message({
            type: "error"
          })
      })
    },
    // 计算年龄
    calcAge(birthdayStr){
      birthdayStr =birthdayStr.substring(0,10);
      let birthday = new Date(birthdayStr.replace(/-/g,"/"));
      let now = new Date();
      let age = now.getFullYear() - birthday.getFullYear() - (now.getMonth() < birthday.getMonth() || (now.getMonth() == birthday.getMonth() && now.getDate() < birthday.getDate()))
      return age;
    },
    // 当选中发生变化时，将客户编号放入customerIdSelected
    handleSelectionChange(val) {
      this.multipleSelection = val

      for (let i = 0; i < this.multipleSelection.length; i++) {
        let id = {}
        id.id = this.multipleSelection[i].id
        this.customerIdSelected[i] = id
      }
    },
    handleGroupSelectionChange(val) {
      this.multipleGroupSelection = val
      this.groupId = this.multipleGroupSelection[0].id
    },
   // 批量删除用户
    deleteCustomerBatch() {
      this.$confirm('此操作将删除用户,是否继续?','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        let array = [];
        for (let i = 0; i < this.customerIdSelected.length; i++) {
          let id = {};
          id.id = this.customerIdSelected[i];
          array[i] = id.id;
        }
        array = {array};
        customer.deleteCustomerBatch(array).then(response => {
          this.initCustomer();
          this.$message({
            type: 'success',
            message: '删除成功',
          })
          return response;
        }).catch((response) => {
          console.log("error:" + response)
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除',
        })
      })
    },
    // 新建分组
    addGroup() {
      group.addGroup(this.group)
        .then((response) => {
          this.initGroup()
          // 重置新建分组输入框
          this.group.groupName = null
          this.addGroupVisible = false
          this.groupOperateVisible = false
          return response
        }).catch((response) => {
          console.log("error:" + response.message);
      })
    },
    // 移动客户
    moveCustomer() {
      // 将消息框关闭
      this.moreVisible = false
      let array = [];

      for (let i = 0; i < this.customerIdSelected.length; i++) {
        let id = {};
        id.id = this.customerIdSelected[i]
        array[i] = id.id
      }
      array = {array};
      customer.moveCustomer(this.groupId, array)
        .then(response => {
          this.initGroup()
            this.$message({
              type: 'success',
              message: "添加成功！",
            })
            return response;
        }).catch((response) => {
          console.log("error:" + response)
      })
    },
  }
};
</script>

<style scoped>
.el-aside {
  background-color: #d3dce6;
  color: var(--el-text-color-primary);
  text-align: center;
  width: 300px;
}

.el-main {
  background-color: #e9eef3;
  color: var(--el-text-color-primary);
  text-align: center;
}

body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}

.handle-box {
  margin: 20px 50px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 120px;
  display: inline-block;
  margin: 10px 20px;
}

.table {
  width: 100%;
  font-size: 14px;
}

.mr10 {
  margin-right: 10px;
}

.my_button{
  margin: 5px 30px;
  width: 180px;
  font-size: 16px
}
.my_table{
  margin: 0px 30px;
}
.groupOperateButton{
  font-size: 20px;
}
#operateDialog {
  margin-left: 600px
}
</style>
